package com.yimo.chromedriver;

import com.yimo.common.util.HttpClient;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import sun.awt.OSInfo;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;

/**
 * create by jsm on 2018/9/27
 */
@Component
public class XiaoHongShu {
    @Value("${chromedriver.driver:/usr/local/bin/chromedriver}")
    private String driverPath;
    private static HashSet <String> urlSet = new HashSet <>();
    private static int cen;
    private static HttpClient httpClient = new HttpClient();

    public  void climb(String url, String savefolder) throws Exception {
        System.setProperty("webdriver.chrome.driver", driverPath);//设置浏览器驱动//设置浏览器驱动
        System.setProperty("webdriver.gecko.driver", driverPath);
        ChromeOptions options = new ChromeOptions();
        if (OSInfo.getOSType().name().equals(OSInfo.OSType.LINUX.name())) {
            options.addArguments("headless");
            options.addArguments("no-sandbox");


        }

        options.addArguments("start-fullscreen");
        ChromeDriver chromeDriver = new ChromeDriver(options);//new 一个浏览器

        chromeDriver.get(url);//打开网页
        d(chromeDriver, savefolder);
        chromeDriver.quit();
        urlSet.clear();
    }

    private static void d(ChromeDriver chromeDriver, String savefolder) throws Exception {
        System.out.println("center d:" + ++cen);
        Thread.sleep(1000L);
        System.out.println("-----------------------"+chromeDriver.getCurrentUrl()+"   pageSource:--------------------");
        System.out.println("pageSource:"+chromeDriver.getPageSource());
        System.out.println("-----------------------pageSource end--------------------");
        List <WebElement> son = findSon(chromeDriver);
        if (son.size() <= 0) {
            chromeDriver.navigate().back();
            System.out.println("back : " + --cen);
            return;
        }
        cself(chromeDriver, savefolder);
        for (int i = 0; i < son.size(); i++) {
            List <WebElement> sonList = findSon(chromeDriver);
            if (sonList != null && sonList.size() < i + 1) {
                continue;
            }
            WebElement webElement = sonList.get(i);
            Thread.sleep(500L);
            webElement.click();

            String sonUrl = chromeDriver.getCurrentUrl();
            if (urlSet.contains(sonUrl)) {
                chromeDriver.navigate().back();

                System.out.println("contains url " + sonUrl);
                continue;
            } else {
                urlSet.add(sonUrl);
                d(chromeDriver, savefolder);
            }

        }
        System.out.println("back : " + --cen);
        chromeDriver.navigate().back();
    }

    private static void cself(ChromeDriver chromeDriver, String savefolder) throws Exception {
        Thread.sleep(2000L);
        Calendar calendar = Calendar.getInstance();
        Date now = new Date();
        calendar.setTime(now);
        String subFolder = savefolder + "/" + calendar.get(Calendar.YEAR) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + calendar.get(Calendar.DAY_OF_MONTH) + "/" + now.getTime();
        List <WebElement> lis = new ArrayList <>();
        try {
            File subFolderFile = new File(subFolder);
            if (subFolderFile.exists() == false) {
                subFolderFile.mkdirs();
            }
            File contentFile = new File(subFolder + "/c" + new Date().getTime() + ".txt");

            FileOutputStream fw = new FileOutputStream(contentFile);
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fw, "UTF-8"));
            String content = chromeDriver.findElement(By.className("content")).getText();
            bw.write(content);
            bw.flush();
            bw.close();

            WebElement carousel = chromeDriver.findElement(By.className("carousel"));
            WebElement ul = carousel.findElement(By.tagName("ul"));
            lis = ul.findElements(By.tagName("li"));
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        if (lis != null && lis.size() > 0) {
            for (WebElement li : lis) {
                try {
                    WebElement image = li.findElement(By.tagName("span"));
                    String background = image.getCssValue("background-image");
                    if (background != null) {
                        background = background.substring("url(\"".length(), background.length() - "\");".length());
                    }

                    InputStream inputStream = httpClient.doGetStream(background);
                    BufferedImage buffer = ImageIO.read(inputStream);
                    ImageIO.write(buffer, "png", new File(subFolder + "/i" + new Date().getTime() + ".png"));
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }

            }
        }
    }


    private static List <WebElement> findSon(ChromeDriver chromeDriver) {
        List <WebElement> sons = chromeDriver.findElements(By.className("picture"));
        return sons;
    }


    public static void main(String[] args) throws Exception {

    }
}
